const express = require('express');
const path = require('path');
const app = express();
const PORT = 8001;
const connectDB = require('./utils/connectDB');
require('dotenv').config();
const cors = require('cors');
const mountRoutes = require('./routers/index.js');

// 全局响应中间件
const ResMiddleWare = require('./utils/resMiddleWare');
app.use(ResMiddleWare);

app.use(express.json());

// 跨域
app.use(cors());

// web文件
app.use(express.static(path.join(__dirname, 'webui')));
app.get('/', (req, res) => {
   res.sendFile(path.join(__dirname, 'webui', 'index.html'));
});

// 注册路由
mountRoutes(app);

// 匹配其他未定义
app.all('*', (req, res) => {
   res.httperr('接口未定义', 404);
});

const start = async () => {
   try {
      await connectDB(process.env.MONGO_URL);
      console.log('Connected to database');
      app.listen(PORT, console.log(`Server is running on port ${PORT}`));
   } catch (error) {
      console.log(error);
   }
};

start();
